package com.dongdongshop.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //创建 ShiroFilterFactoryBean 过滤器工厂
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //创建Map集合 注意创建有序集合
        Map<String,String> map = new LinkedHashMap<>();

        //给map里 路径 和 权限,anon代表不需要登录,authc代表需要登录

        map.put("/js/**", "anon");
        map.put("/img/**", "anon");
        map.put("/css/**", "anon");
        map.put("/plugins/**", "anon");

        map.put("/index","anon");
        map.put("/login/login","anon");

        map.put("/login/logout", "logout");

        map.put("/**","authc");


        //配置的过滤器,哪些可以不用登录,哪些需要登录,哪些路径必须需要权限等等
//        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //当路径没有登录,所跳转的登录路径
        shiroFilterFactoryBean.setLoginUrl("login/toLogin");
        //将安全管理器放入过滤器工厂
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 当没有权限时调用的方法
//        shiroFilterFactoryBean.setUnauthorizedUrl("/personController/unauthorizedUrl");
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    @Bean
    public LoginRealm realm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        LoginRealm realm = new LoginRealm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher);
        return realm;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashIterations(3);
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }

    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
